package com.qf.controller;

import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.Base64;
import com.qf.util.ResponseUtil;
import com.qf.util.UUID;
import com.qf.util.VerifyCodeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@RestController
@RequestMapping("/admin/auth")
public class AdminAuthController {

    @Autowired
    DtsPermissionService permissionService;

    @Autowired
    DtsRoleService roleService;


    @RequestMapping("/info")
    public Object info(){

        //获取主体对象（包含一切对外的接口）
        Subject subject = SecurityUtils.getSubject();
        //获取dtsAdmin（登录成功的对象）
        DtsAdmin admin = (DtsAdmin) subject.getPrincipal();
        //获取角色id数组
        Integer[] roleIds = admin.getRoleIds();
        Set<String> perms = permissionService.findPermsByRoleIds(roleIds);
        Set<String> roles = roleService.findRolesByRoleIds(roleIds);


        Map<String, Object> data = new HashMap<>();
        data.put("name", admin.getUsername() );
        data.put("perms", perms);
        data.put("avatar", admin.getAvatar());
        data.put("roles", roles);

        return ResponseUtil.ok(data);
    }



    @RequestMapping("/login")
    public Object login(@RequestBody Map<String,String> map){
        //校验验证码
        //用户输入的验证码
        String code = map.get("code");
        //获取服务端缓存中的验证码
        String uuid = map.get("uuid");
        String cachedCaptcha = CaptchaCodeManager.getCachedCaptcha(uuid);
        if(cachedCaptcha == null || !cachedCaptcha.equalsIgnoreCase(code)){
            return ResponseUtil.fail(-1, "验证码已过期,请重新获取验证码");
        }

        //获取用户名和密码
        String username = map.get("username");
        String password = map.get("password");


        try {
            //校验用户名密码
            //获取主体对象（对象包含了一切对外的接口）
            Subject subject = SecurityUtils.getSubject();
            //创建token对象
            UsernamePasswordToken token = new UsernamePasswordToken(username ,password);
            //执行登录操作，跟数据库中的用户名和密码进行校验
            subject.login(token);

            Serializable id = subject.getSession().getId();
            System.out.println(subject.hasRole("超级管理员"));
            return ResponseUtil.ok(id);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1, "未知的用户名");
        } catch (CredentialsException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1, "密码错误");
        }
        catch (LockedAccountException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1, "账户已锁定");
        }catch (AuthenticationException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1, "认证失败，请重新认证");
        }

    }

    /**
     * 获取验证码
     * @return
     */
    @RequestMapping("/captchaImage")
    public Object captchaImage() throws IOException {
        //随机得到两位验证码
        String verifyCode = VerifyCodeUtils.generateVerifyCode(2);
        String uuid = UUID.randomUUID().toString();
        //把验证码存储到缓存中
        CaptchaCodeManager.addToCache(uuid  , verifyCode, 5 );

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //生成图片
        VerifyCodeUtils.outputImage(111,  36, outputStream, verifyCode);

        Map<String, Object> data = new HashMap<>();
        data.put("uuid", uuid);
        data.put("img", Base64.encode(outputStream.toByteArray()));
        return ResponseUtil.ok(data);
    }

    @RequestMapping("/logout")
    public Object logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return  ResponseUtil.ok();
    }
}
